<template>
  <div class="chart-container">
    <div v-if="nodata" class="no-data">No Data</div>
    <div v-else class="chart-wrapper">
      <!-- 操作栏 -->
      <div class="chart-operation">
        <div class="mode-buttons">
          <button 
            :class="['mode-btn', { active: currentMode === 'merge' }]"
            @click="switchMode('merge')"
          >
            📈 合并查看
          </button>
          <button 
            :class="['mode-btn', { active: currentMode === 'split' }]"
            @click="switchMode('split')"
          >
            📊 拆分查看
          </button>
        </div>
      </div>

      <!-- 图表区：确保拆分图表DOM先渲染并绑定 -->
      <div :class="['chart-content', { 'split-layout': currentMode === 'split' }]">
        <!-- 合并图表：key=chartmain -->
        <div 
          v-if="currentMode === 'merge'" 
          ref="mergeChartRef"
          class="merge-chart"
        ></div>
        <div v-else class="split-charts">
          <!-- 拆分图表：通过ref回调将DOM存入dictChart，确保key正确 -->
          <div 
            v-for="(item, index) in tempPointList" 
            :key="`chart-item-${index}`" 
            class="split-chart-item"
            :ref="el => {
              const chartKey = `chart${String(index + 1).padStart(2, '0')}`;
              if (el) {
                dictChart[chartKey] = el; // DOM存在时存入字典
                console.log(`绑定拆分图表DOM：${chartKey}`, el);
              }
            }"
          ></div>
        </div>
      </div>

      <!-- 合并模式图例（筛选开关） -->
      <div class="chart-legend" v-if="currentMode === 'merge'">
        <input 
          type="text" 
          v-model="legendSearch" 
          class="legend-search"
          placeholder="搜索监控点..."
        >
        <!-- 4. 模板：绑定原始索引，解决搜索后勾选错位 -->
<div class="legend-list">
  <label 
    v-for="item in filteredLegendList" 
    :key="`switch-${item.originalIndex}`" 
    class="legend-item"
  >
    <input 
      type="checkbox" 
  
      :checked="switchDict[`switch${String(item.originalIndex + 1).padStart(2, '0')}`]"
  
      @change="(e) => handleSwitchChange(item.originalIndex, e.target.checked)"
    >
    <span class="legend-color" :style="{ background: item.color }"></span>
    <span class="legend-name">{{ item.name }}</span>
  </label>
</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, computed, nextTick } from 'vue';
import * as echarts from 'echarts';

// Props
const props = defineProps({
  visible: { type: Boolean, default: false },
});

// ---------------------- 核心字典：实例+开关状态 ----------------------
// 实例字典：先存DOM，初始化后替换为ECharts实例
let dictChart = {};

// 开关状态字典：key=switch01-switch09，对应9个监控点显隐，默认true
let switchDict = {
  switch01: true,
  switch02: true,
  switch03: true,
  switch04: true,
  switch05: true,
  switch06: true,
  switch07: true,
  switch08: true,
  switch09: true,
};

// 合并图表ref变量
const mergeChartRef = ref(null);

// 核心响应式状态
const nodata = ref(false);
const currentMode = ref('merge');
const legendSearch = ref('');
const chartData = ref([]);

// 监控点配置（与chart01-chart09、switch01-switch09一一对应）
const tempPointList = ref([
  { name: '前上区温度', key: 'tempFrontUp', color: '#FF005A', lineType: 'solid' }, // switch01/chart01
  { name: '前中区温度', key: 'tempFrontMid', color: '#FF7D00', lineType: 'solid' }, // switch02/chart02
  { name: '前下区温度', key: 'tempFrontDown', color: '#FFEE00', lineType: 'solid' }, // switch03/chart03
  { name: '中上区温度', key: 'tempMidUp', color: '#00E4FF', lineType: 'dashed' }, // switch04/chart04
  { name: '中心区温度', key: 'tempCenter', color: '#00B42A', lineType: 'dashed' }, // switch05/chart05
  { name: '中下区温度', key: 'tempMidDown', color: '#0052D9', lineType: 'dashed' }, // switch06/chart06
  { name: '后上区温度', key: 'tempBackUp', color: '#7209B7', lineType: 'dotted' }, // switch07/chart07
  { name: '后中区温度', key: 'tempBackMid', color: '#F56565', lineType: 'dotted' }, // switch08/chart08
  { name: '后下区温度', key: 'tempBackDown', color: '#38B2AC', lineType: 'dotted' }, // switch09/chart09
]);

// 过滤后的图例
const filteredLegendList = computed(() => {
  const lowerVal = legendSearch.value.toLowerCase().trim();
  // 映射时保留原始index（对应switch01-switch09）
  return tempPointList.value
    .map((item, originalIndex) => ({
      ...item,
      originalIndex // 存储原始索引，避免过滤后错位
    }))
    .filter(item => item.name.toLowerCase().includes(lowerVal));
});

// 时间格式化工具函数
const formatTime = (timeStr, type = 'time') => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  if (isNaN(date.getTime())) return '';
  const pad = (n) => n.toString().padStart(2, '0');
  const [h, m, s] = [pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds())];
  const [mm, dd] = [pad(date.getMonth() + 1), pad(date.getDate())];
  return type === 'time' ? `${h}:${m}:${s}` : `${mm}-${dd} ${h}:${m}:${s}`;
};

// ---------------------- 图表核心逻辑（修复DOM绑定） ----------------------
// 合并图表Option（直接读取switchDict控制显隐）
const getMergeOption = () => ({


  title: { text: '监控点温度曲线', left: 'center', textStyle: { color: '#00e4ff', fontSize: 16 } },
  grid: { top: '15%', left: '5%', right: '5%', bottom: '15%' },
  tooltip: {
    trigger: 'axis',
    formatter: (params) => {
      
      const time = formatTime(chartData.value[params[0].dataIndex]?.createdTime);
      return `${time}<br/>${params.map(p => `${p.seriesName}: ${p.value}℃`).join('<br/>')}`;
    }
  },
  animation: false,
    animationUpdate: false,
  xAxis: {
    type: 'category',
    data: chartData.value.map(d => formatTime(d.createdTime, 'dateTime')),
    axisLabel: { color: '#bbdaff', fontSize: 11, interval: chartData.value.length > 20 ? 'auto' : 0 }
  },
  yAxis: {
    type: 'value',
    min: 0,
    max: 800,
    axisLabel: { color: '#bbdaff', formatter: '{value}℃' }
  },
  series: tempPointList.value
    .map((item, index) => {
      const switchKey = `switch${String(index + 1).padStart(2, '0')}`;
      // 只返回开关为true的系列配置
      if (switchDict[switchKey]) {
        return {
          name: item.name,
          key: item.key,
          type: 'line',
          data: chartData.value.map(d => d[item.key] ?? 0),
          itemStyle: { color: item.color },
          lineStyle: { color: item.color, type: item.lineType, width: 2 },
          symbol: 'none',
          smooth: true,
        };
      }
    })
    .filter(Boolean) // 过滤掉undefined（开关为false的项）
});

// 拆分图表Option
const getSplitOption = (item) => ({
  title: { 
    text: item.name,
    left: 'center',
    textStyle: { color: item.color, fontSize: 13, fontWeight: 500 }
  },
  grid: { top: '20%', left: '12%', right: '8%', bottom: '15%' },
  tooltip: {
    trigger: 'axis',
    formatter: (params) => {
      const time = formatTime(chartData.value[params[0].dataIndex]?.createdTime);
      return `${time}<br/>温度: ${params[0].value}℃`;
    },
    animation: false // 关闭tooltip动画
  },
  animation: false,
    animationUpdate: false,
  xAxis: {
    type: 'category',
    data: chartData.value.map(d => formatTime(d.createdTime)),
    axisLabel: { color: '#bbdaff', fontSize: 9, rotate: 30 }
  },
  yAxis: {
    type: 'value',
    min: Math.max(0, Math.min(...chartData.value.map(d => d[item.key] ?? 0).filter(v => !isNaN(v))) - 20) || 0,
    max: Math.min(800, Math.max(...chartData.value.map(d => d[item.key] ?? 0).filter(v => !isNaN(v))) + 20) || 800,
    axisLabel: { color: '#bbdaff', formatter: '{value}℃' }
  },
  series: [{
    name: item.name,
    type: 'line',
    data: chartData.value.map(d => d[item.key] ?? 0),
    itemStyle: { color: item.color },
    lineStyle: { color: item.color, type: item.lineType, width: 2 },
    symbol: 'none',
    smooth: true,
  }]
});

// 初始化合并图表（精简版）
const initMergeChart = () => {
  if (!mergeChartRef.value) {
    console.warn('合并图表DOM未找到');
    return;
  }
  //console.log('初始化合并图表：chartmain');
  dictChart.chartmain = echarts.init(mergeChartRef.value);
  dictChart.chartmain.setOption(getMergeOption(),true );
};

// 初始化单个拆分图表（确保DOM已存入字典）
const initSplitChart = (item, index) => {
  const chartKey = `chart${String(index + 1).padStart(2, '0')}`;
  const dom = dictChart[chartKey]; // 从字典取已绑定的DOM
  
  if (!dom) {
    console.warn(`拆分图表DOM未找到：${chartKey}`);
    return;
  }
  
  //console.log(`初始化拆分图表：${chartKey}（${item.name}）`);
  dictChart[chartKey] = echarts.init(dom); // 替换为ECharts实例
  dictChart[chartKey].setOption(getSplitOption(item));
};

// 批量初始化所有拆分图表（确保DOM绑定完成后执行）
const initAllSplitCharts = async () => {
  // 等待DOM渲染和ref回调执行完成
  await nextTick();
  //console.log('开始初始化所有拆分图表，当前字典：', Object.keys(dictChart));
  
  tempPointList.value.forEach((item, index) => {
    initSplitChart(item, index);
  });
  
  // 初始化后打印字典，验证9个图表是否存在
  setTimeout(() => {
    console.log('拆分图表初始化完成，最终字典：', Object.keys(dictChart));
  }, 100);
};

// 切换模式（确保DOM切换后再初始化）
const switchMode = async (mode) => {
  if (currentMode.value === mode) return;
  currentMode.value = mode;
  
  // 等待DOM切换完成
  await nextTick();
  
  if (mode === 'split') {
    initAllSplitCharts(); // 切换到拆分模式时初始化（如果未初始化）
  }
  else
   initMergeChart()
  
  setTimeout(resizeAllCharts, 100);
};

// 开关变化处理（直接更新字典+setOption）
const handleSwitchChange = (index, isShow) => {
  const switchKey = `switch${String(index + 1).padStart(2, '0')}`;
  switchDict[switchKey] = isShow;
  let option = getMergeOption()
  dictChart.chartmain.clear()
  dictChart.chartmain.setOption(option);
};

// 统一resize所有图表
const resizeAllCharts = () => {
  //console.log('统一resize所有图表，当前字典key：', Object.keys(dictChart));
  Object.values(dictChart).forEach(chart => {
    chart && chart.resize && chart.resize();
  });
};

// 父组件更新数据
const updateEcharts =async (data) => {
  const validData = Array.isArray(data) ? data : [];
  chartData.value = validData;
  nodata.value = validData.length === 0;
  
  if (!validData.length) return;
  
  // 更新所有图表
  //dictChart.chartmain?.setOption(getMergeOption());
  await nextTick();
  let mode = currentMode.value
  if (mode === 'split') {
    initAllSplitCharts(); // 切换到拆分模式时初始化（如果未初始化）
    
  }
  else
   initMergeChart()
  



};

// ---------------------- 初始化逻辑（修复时机问题） ----------------------
onMounted(async () => {
  //console.log('初始化echarts，开始绑定DOM');
  
  // 等待DOM渲染完成（确保合并图表和拆分图表DOM都已绑定）
  await nextTick();
  
  // 初始化合并图表（始终渲染，可直接初始化）
  initMergeChart();
  
  // 如果初始模式是拆分，初始化拆分图表；否则后续切换时初始化
  if (currentMode.value === 'split') {
    initAllSplitCharts();
  } else {
    //console.log('初始模式为合并，拆分图表将在切换模式时初始化');
  }
  

  // 延迟500ms resize
  setTimeout(() => {
    resizeAllCharts();
  }, 500);
});

// 监听弹框显示状态
watch(() => props.visible, async (isVisible) => {
  if (isVisible && chartData.value.length) {
    await nextTick();
    setTimeout(resizeAllCharts, 500);
  }
}, { immediate: true });

// 暴露方法
defineExpose({ updateEcharts });
</script>

<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 600px;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
}

.no-data {
  height: 300px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #e0e0e0;
  color: #999;
  font-size: 16px;
  border-radius: 4px;
  background: #fafafa;
}

.chart-wrapper {
  display: flex;
  flex-direction: column;
  gap: 15px;
  height: 100%;
  box-sizing: border-box;
}

.chart-operation {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 8px;
}

.mode-buttons {
  display: flex;
  gap: 15px;
}

.mode-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 4px;
  background: #f5f5f5;
  color: #333;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  transition: all 0.2s ease;

  &:hover { background: #e9e9e9; }
  &.active { background: #00e4ff; color: #000; font-weight: 500; box-shadow: 0 2px 8px rgba(0, 228, 255, 0.3); }
}

.chart-content {
  flex: 1;
  position: relative;
  box-sizing: border-box;

  .merge-chart {
    width: 100%;
    height: 100%;
    min-height: 450px;
    border-radius: 4px;
    background: rgba(0, 0, 0, 0.02);
    border: 1px solid rgba(255, 255, 255, 0.1);
    box-sizing: border-box;
  }

  &.split-layout {
    .split-charts {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      grid-template-rows: repeat(3, 1fr);
      gap: 12px;
      height: 100%;
      min-height: 500px;
      box-sizing: border-box;

      .split-chart-item {
        width: 100%;
        height: 100%;
        min-height: 130px;
        border-radius: 4px;
        background: rgba(0, 0, 0, 0.02);
        border: 1px solid rgba(255, 255, 255, 0.1);
        box-sizing: border-box;
      }
    }
  }
}

.chart-legend {
  padding: 0 8px;

  .legend-search {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
    box-sizing: border-box;
    font-size: 14px;
    color: #333;

    &::placeholder { color: #999; }
    &:focus { outline: none; border-color: #00e4ff; box-shadow: 0 0 0 2px rgba(0, 228, 255, 0.2); }
  }

  .legend-list {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    max-height: 80px;
    overflow-y: auto;
    padding: 4px 0;

    &::-webkit-scrollbar { width: 4px; height: 4px; }
    &::-webkit-scrollbar-thumb { background: #ccc; border-radius: 2px; }

    .legend-item {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      color: #bbdaff;
      cursor: pointer;
      font-size: 13px;
      white-space: nowrap;

      input {
        width: 14px;
        height: 14px;
        accent-color: #00e4ff;
        cursor: pointer;
      }

      .legend-color {
        width: 14px;
        height: 14px;
        border-radius: 50%;
        border: 1px solid #fff;
      }

      .legend-name:hover { color: #00e4ff; transition: color 0.2s; }
    }
  }
}

@media (max-width: 1200px) {
  .chart-content.split-layout .split-charts { grid-template-columns: repeat(2, 1fr); }
}

@media (max-width: 768px) {
  .chart-content.split-layout .split-charts { grid-template-columns: 1fr; }
  .chart-container { min-height: 900px; }
}
</style>